package com.fce.fcesystem.controller;

import com.alibaba.fastjson.JSON;
import com.fce.fcesystem.ex.UsernameDuplicateException;
import com.fce.fcesystem.pojo.Menu;
import com.fce.fcesystem.pojo.Role;
import com.fce.fcesystem.pojo.RoleMenu;
import com.fce.fcesystem.pojo.User;
import com.fce.fcesystem.service.IUserService;
import com.fce.fcesystem.utils.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@EnableAsync
@RestController
@RequestMapping("user")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    /**
     * @description:注册
     **/
    @RequestMapping("register")
    public JsonResult<Void> register(User user) {
        userService.register(user);
        return new JsonResult<Void>(OK);
    }

    /**
     * @description:登录
     **/
    @RequestMapping("login")
    public JsonResult<String[]> login(String account, String password, HttpServletRequest httpServletRequest){
        return userService.login(account, password,httpServletRequest);
    }

    /**
     * @description:修改用户密码
     **/
    @RequestMapping("updatePwd")
    public JsonResult<Void> updatePwd(String oldPassword, String newPassword, HttpSession session){
        Integer id = getUidFromSession(session);
        userService.updateUserPassword(id,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    /**
     * @查询管理员
     **/
    @RequestMapping("getAdmins")
    public JsonResult<List<User>> getAdmins(String name){
        List<User> list = userService.getAdmins(name);
        return new JsonResult<>(OK,list);
    }

    /**
     * @查询用户信息
     **/
    @RequestMapping("selectUsers")
    public JsonResult<List<User>> selectUsers(String name){
        List<User> list = userService.selectUsers(name);
        return new JsonResult<>(OK, list);
    }

    /**
     * @删除用户信息
     **/
    @RequestMapping("deleteUser")
    public JsonResult<Void> deleteUser(Integer userId){
        User user = userService.selectUserById(userId);
        if (user.getUserId() != null) {
            userService.deleteUserRole(userId,user.getRoleId());
        }
        userService.deleteUser(userId);
        return new JsonResult<>(OK);
    }

    /**
     * @更新头像
     **/
    @RequestMapping("headUpload")
    public JsonResult<User> headUpload(MultipartFile file, String userName) throws IOException {
        userService.updateHref(file, userName);
        return new JsonResult<>(OK, userService.selectUserByAccount(userName));
    }

    /**
     * @更新用户信息
     **/
    @RequestMapping("updateUser")
    public JsonResult<Void> updateUser(Integer userId, Integer oldRoleId, Integer newRoleId){
        userService.updateUser(userId, oldRoleId, newRoleId);
        return new JsonResult<>(OK);
    }

    /**
     * @更新用户信息
     **/
    @RequestMapping("updateUserInfo")
    public JsonResult<Void> updateUserInfo(Integer userId, String userName, String email,String phone){
        userService.updateUserInfo(userId, userName, email, phone);
        return new JsonResult<>(OK);
    }

    /**
     * @保存验证码
     **/
    @RequestMapping("emailKey")
    public JsonResult<Void> emailKey(String key,String userName){
        userService.emailLoad(key, userName);
        return new JsonResult<>(OK);
    }

    /**
     * 发送邮件
     **/
    @RequestMapping("sendEmail")
    public JsonResult<Void> sendEmail(String userName,String email){
        if (!userService.selectUserByAccount(userName).getEmail().equals(email)){
            throw new UsernameDuplicateException("输入的邮箱地址与绑定邮箱不匹配！");
        }
        return new JsonResult<>(OK);
    }

    /**
     * @更新密码
     **/
    @RequestMapping("updatePwdByKey")
    public JsonResult<Void> updatePwdByKey(String userName,String email,String key,String password){
        userService.updatePwdByKey(userName, email, key, password);
        return new JsonResult<>(OK);
    }

    /**
     * @description:获取权限菜单
     *
     **/
    @RequestMapping("loadMenu")
    public JsonResult<List<Menu>> loadMenu(){
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        User rolesByAccount = userService.findRolesByAccount((String) principal);
        List<Role> roles = rolesByAccount.getRoles();
        List<Menu> menuList = userService.loadMenu(roles.get(0).getId());
        return new JsonResult<>(OK,menuList);
    }

    /**
     * @description:获取子菜单
     *
     **/
    @RequestMapping("childMenu")
    public JsonResult<List<Menu>> getChildMenu(@RequestParam("parentId") Integer parentId){
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        User rolesByAccount = userService.findRolesByAccount((String) principal);
        List<Role> roles = rolesByAccount.getRoles();
        List<Menu> menuChildList = userService.loadChildMenu(parentId,roles.get(0).getId());
        return new JsonResult<>(OK,menuChildList);
    }

    /**
     * @加载所有角色菜单
     **/
    @RequestMapping("permissionList")
    public  JsonResult<List<RoleMenu>> permissionList(@RequestParam("roleName")String roleName) {
        List<RoleMenu> permissionList = userService.getPermissionList(roleName);
        permissionList.forEach(ps->{
            List<Menu> menus = ps.getMenus();
            String jsonString = JSON.toJSONString(menus);
            ps.setMenusString(jsonString);
        });
        return new JsonResult<>(OK,permissionList);
    }

    /**
     * @更新角色
     **/
    @RequestMapping("updatePermission")
    public JsonResult<Void> updatePermission(Integer roleId, String roleName, Integer[] menus){
        userService.updatePermission(roleId,roleName,menus);
        return new JsonResult<>(OK);
    }

    /**
     * @删除角色
     **/
    @RequestMapping("deletePermission")
    public JsonResult<Void> deletePermission(Integer roleId){
        userService.deletePermission(roleId);
        return new JsonResult<>(OK);
    }

    /**
     * @新增角色
     **/
    @RequestMapping("insertPermission")
    public JsonResult<Void> insertPermission(String roleName,Integer[] menus) {
        userService.insertPermission(roleName,menus);
        return new JsonResult<>(OK);
    }

}

